package vip.xiaonuo.common.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.RandomUtil;
import vip.xiaonuo.common.cache.CommonCacheOperator;

import java.util.concurrent.TimeUnit;

public class CommonGeneratePayOrderNoUtil {

    private static final String ORDER_PREFIX = "pay-order-no:";

    private static final String DATE_FORMAT = "yyyyMMdd";

    private static final String DATE_FORMAT_WITH_TIME = "yyyyMMddHHmmss";

    /**
     * 生成订单号
     *
     * @param redisOperator redis操作
     * @param orderPrefix   订单号前缀
     * @return
     */
    public static String generatePayOrderNo(CommonCacheOperator redisOperator, String orderPrefix) {
        return generatePayOrderNo(redisOperator, orderPrefix, 6);
    }


    /**
     * 生成订单号
     *
     * @param redisOperator redis操作
     * @param orderPrefix   订单号前缀
     * @param suffixLength  后缀长度
     * @return
     */
    public static String generatePayOrderNo(CommonCacheOperator redisOperator, String orderPrefix, int suffixLength) {

        String orderNo = null;
        boolean hasOrder = true;
        String redisKey = ORDER_PREFIX + DateUtil.format(DateUtil.date(), DATE_FORMAT);

        /**
         * 生成不重复的订单号
         */
        while (hasOrder) {
            orderNo = orderPrefix + DateUtil.format(DateUtil.date(), DATE_FORMAT_WITH_TIME) + RandomUtil.randomInt(suffixLength);
            hasOrder = redisOperator.isValueInSet(redisKey, orderNo);
        }

        // 添加到redis
        redisOperator.setCacheSet(redisKey, orderNo);

        // 设置过期时间
        redisOperator.expire(redisKey, 1, TimeUnit.DAYS);

        return orderNo;
    }

}
